package com.lagou.edu.controller;

import com.lagou.edu.dao.UserRepository;
import com.lagou.edu.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@Controller
public class DemoController  {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/loginpage")
    public String loginpage()
    {
        return "login";
    }

    @PostMapping("/login")
    public String login(@RequestParam("name")String name,@RequestParam("phone")String phone,
        HttpSession session,Model model)
    {
        User byNameAndPhone = userRepository.findByNameAndPhone(name, phone);
        if(byNameAndPhone==null)
        {return "login";}

        model.addAttribute("users",userRepository.findAll());
        session.setAttribute("user",byNameAndPhone);

        return "users";
    }

    @GetMapping("/delete/{id}")
    public String deleteById(@PathVariable("id")Long id, Model model)
    {
        userRepository.deleteById(id);
        model.addAttribute("users",userRepository.findAll());
        return "users";
    }

    @PostMapping("/update")
    public String update(@RequestParam("id")Long id,@RequestParam("name")String name,
            @RequestParam("address")String address,@RequestParam("phone")String phone,
            Model model)
    {
        User user=new User(id,name,address,phone);
        userRepository.save(user);
        model.addAttribute("users",userRepository.findAll());
        return "users";
    }

}
